<template>
  <!-- 添加考勤点 -->
  <el-dialog
    :title="titleMap[mode]"
    v-model="visible"
    width="40%"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <el-form
      :model="form"
      :rules="rules"
      :disabled="mode == 'show'"
      ref="dialogForm"
      label-width="auto"
      label-position="right"
      class="noFlex"
    >
      <el-form-item label="考勤点名称" prop="pointsName">
        <el-input
          v-model="form.pointsName"
          clearable
          placeholder="请输入考勤点名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="fullAddress">
        <el-input
          v-model="form.fullAddress"
          type="textarea"
          rows="3"
          clearable
          placeholder="请输入详细地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="有效范围(米)" prop="effectiveRange">
        <el-input
          v-model="form.effectiveRange"
          clearable
          placeholder="请输入有效范围"
          disabled
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        v-if="mode != 'show'"
        type="primary"
        :loading="isSaveing"
        @click="submit()"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>

<script>
import loadBMap from '@/utils/loadBMap.js'
import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
  securityJsCode: '64ad071874b69e469ad892b5ce0b7a4b', // 你的密钥
}
export default {
  emits: ['success', 'closed'],
  data () {
    return {
      mode: "add",
      titleMap: {
        add: '新增',
        edit: '编辑',
        show: '查看'
      },
      visible: false,
      isSaveing: false,
      //表单数据
      form: {
        pointsName: "",//考勤点名称
        fullAddress: "",//详细地址
        effectiveRange: '1000',//有效范围/米
        latitude: '',//纬度
        longitude: '',//纬度
      },
      //验证规则
      rules: {
        pointsName: [
          { required: true, message: '请输入考勤点名称' }
        ],
        fullAddress: [
          { required: true, message: '请输入详细地址' }
        ],
        effectiveRange: [
          { required: true, message: '请输入有效范围' }
        ]
      },
      location: {}//定位经纬度
    }
  },
  async mounted () {
    await loadBMap()
  },
  methods: {
    //显示
    open (mode = 'add') {
      this.mode = mode
      this.visible = true
      return this
    },

    // 高德地图  获取坐标
    initMap () {
      return new Promise((resolve, reject) => {
        AMapLoader.load({
          key: "8d2e4b83d50e3000adac59b9c701dcb6", // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ['AMap.Geocoder', 'AMap.Geolocation'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        }).then((AMap) => {

          let geocoder = new AMap.Geocoder({ enableHighAccuracy: true, city: '全国' })//是否使用高精度定位
          geocoder.getLocation(this.form.fullAddress, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              // 经纬度
              let lng = result.geocodes[0].location.lng
              let lat = result.geocodes[0].location.lat
              resolve({
                lat,
                lng
              })
            } else {
              reject('考勤点定位失败，请确认地址重新定位')
            }
          })
        }).catch(e => {
          console.log(e)
        })
      })
    },

    //表单提交方法
    async submit () {
      console.log(2222)
      this.location = await this.initMap()
      console.log(this.location)
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true
          this.form.latitude = this.location.lat
          this.form.longitude = this.location.lng
          console.log(this.form)
          let res = null
          if (this.mode == 'add') {
            res = await this.$API.attendance.addAttendanceLocation.post(this.form)
          } else if (this.mode == 'edit') {
            res = await this.$API.attendance.updateAttendanceLocation.post(this.form)
          }
          console.log(res)
          this.isSaveing = false
          if (res.code == 200) {
            this.$emit('success', this.form, this.mode)
            this.visible = false
            this.$message.success("操作成功")
          }
        }
      })
    },
    //表单注入数据
    setData (data) {
      this.form = data
    },

    // 根据地址获取经纬度  - 百度
    getPointByAddress () {
      // // 创建地理编码实例
      // // eslint-disable-next-line no-undef
      // const myGeo = new BMap.Geocoder()
      // return new Promise((resolve, reject) => {
      //   // 对地址进行地理编码
      //   myGeo.getPoint(this.form.fullAddress, (point) => {
      //     if (point) {
      //       // 地理编码成功，返回经纬度坐标对象
      //       resolve(point)
      //     } else {
      //       // 地理编码失败
      //       // this.$message.error("考勤点定位失败，请确认地址重新定位")
      //       reject('考勤点定位失败，请确认地址重新定位')

      //     }
      //   }, '全国')
      // })
    },
  }
}
</script>

<style>
</style>
